作者:陈广 日期:2019-3-29
通过本实验,掌握 ISO15693 电子标签的读卡操作。
上次实验我们演示了如何向标签中单个数据块写入数据,以及如何将未知长度的数据写入标签。本次实验,我们将上次写入的数据读出来。
新建一个控制台应用程序,输入如下代码:
using HBLib;
using HBLib.HR8002Reader;
using HBLib.ISO15693;
using System;
using System.Text;
using System.Threading.Tasks;
namespace I15693CmdDemo
{
class Program
{
static ComPort com = new ComPort("COM3", 19200, 3000);
static Reader reader;
static I15693 i15693;
static void Main(string[] args)
{
com.Open();
reader = new Reader(0x00, com);
i15693 = new I15693(0x00, com);
ReadSingleBlock(0);
Console.ReadLine();
}
private static async Task ReadSingleBlock(byte blockNum)
{
await reader.ChangeToISO15693Async();
var info = await i15693.InventoryWithoutAFIAsync();
if (info.ReturnValue != ReturnMessage.Success)
{
Console.WriteLine("选卡失败!");
return;
}
await i15693.SelectAsync(info.UID); //让询查到的标签进入选中状态
var info1 = await i15693.ReadSingleBlockAsync(I15693BlockLen.Four, blockNum);
Console.WriteLine(info1.GetBlockDataStr());
}
}
}
运行结果:
0A 0B 0C 0D
这正好是上个实验中我们在 0 块写入的数据。
HR8002 读写器内置了读取多个数据块的功能,可以让在读多个数据块时省去很多麻烦。下面我们将上个实验中从 1 块开始写入的数据读出来,并还原为字符串。将上述程序更改如下:
using HBLib;
using HBLib.HR8002Reader;
using HBLib.ISO15693;
using System;
using System.Text;
using System.Threading.Tasks;
namespace I15693CmdDemo
{
class Program
{
static ComPort com = new ComPort("COM3", 19200, 3000);
static Reader reader;
static I15693 i15693;
static void Main(string[] args)
{
com.Open();
reader = new Reader(0x00, com);
i15693 = new I15693(0x00, com);
GetStringFromCard(1);
Console.ReadLine();
}
//参数blockNum表示从哪个数据块开始读
private static async Task GetStringFromCard(byte blockNum)
{
await reader.ChangeToISO15693Async();
var info = await i15693.InventoryWithoutAFIAsync();
if (info.ReturnValue != ReturnMessage.Success)
{
Console.WriteLine("选卡失败!");
return;
}
await i15693.SelectAsync(info.UID); //让询查到的标签进入选中状态
//首先读取第一个数据块以获取整个字节数组的长度
var info1 = await i15693.ReadSingleBlockAsync(I15693BlockLen.Four, blockNum);
int len = info1.BlockData[0] + 1;
//计算需要读取的块的个数
int count = len / 4 + ((len % 4 == 0) ? 0 : 1);
var info2 = await i15693.ReadMultipleBlockAsync(I15693BlockLen.Four, blockNum, (byte)count); //读数据
byte[] data = info2.GetBlockData();
string str = Encoding.Unicode.GetString(data, 1, info1.BlockData[0]);
Console.WriteLine(str);
}
}
}
运行结果:
IOT小分队:www.iotxfd.cn
从运行结果可知,读出来的正是我们上个实验所写入的字符串。
;思考题(难度 **):读取数据时,读取的块的个数不能超过 12 个。本实验并没有考虑超过 12 个块的处理方式。请加长写入的字符串,使其占用超过 12 个块。并更改本程序,使其能正确读出超长字符串。